package com.example.demo.Client;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取指定的Client和关闭连接
 */
public class TransportTemplate {

    public final static String HOST = "127.0.0.1";

    //http请求的端口是9200，客户端是9300
    public final static int PORT = 9300;

    private static TransportClient client = null;

    /**
     * 获取连接
     * @return
     * @throws UnknownHostException
     */
    public static TransportClient getClient() {
        try {
            client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(
                    new InetSocketTransportAddress(InetAddress.getByName(HOST),PORT));
            System.out.println("连接信息:" + client.toString());
            return client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
            return null;
    }

    /**
     * 关闭连接
     */
    public static void closeClient() {
        if(null != client) {
            System.out.println("执行关闭连接操作...");
            client.close();
        }
    }

}
